package cn.edu.buu.hospital.web;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录检查过滤器，使用标准的javax.servlet.Filter接口实现
 * 功能：拦截所有请求，检查用户是否已登录（通过检查session中的loginAdmin对象）
 * 例外：指定的排除路径不需要登录检查，包括登录页面、登录操作和登出操作
 * 替代了原来的HandlerInterceptor实现
 */
@WebFilter(filterName = "CheckAdminLoginFilter", 
           urlPatterns = "/*",
           initParams = {
               @WebInitParam(name = "excludedPaths", value = "/toAdminLogin,/adminLogin,/logout,/auth/register,/auth/login,/toDoctorLogin,/doctorLogin,/doctorLogout,/statics")
           })
public class CheckAdminLoginFilter implements Filter {
    
    private String excludedPaths;
    private String[] excludedPathArray;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 获取排除路径参数
        excludedPaths = filterConfig.getInitParameter("excludedPaths");
        if (excludedPaths != null && !excludedPaths.isEmpty()) {
            excludedPathArray = excludedPaths.split(",");
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        // 获取请求路径
        String path = httpRequest.getServletPath();
        System.out.println("Filter processing path: " + path);
        
        // 检查是否是排除路径
        boolean isExcluded = false;
        if (excludedPathArray != null) {
            for (String excludedPath : excludedPathArray) {
                // 对于静态资源路径，使用前缀匹配
                if (excludedPath.equals("/statics")) {
                    if (path.startsWith("/statics")) {
                        isExcluded = true;
                        break;
                    }
                } else if (path.equals(excludedPath)) {
                    // 对于其他路径，使用完全匹配
                    isExcluded = true;
                    break;
                }
            }
        }
        
        // 如果是排除路径，直接放行
        if (isExcluded) {
            chain.doFilter(request, response);
            return;
        }
        
        // 检查登录状态 - 检查所有类型的登录用户
        HttpSession session = httpRequest.getSession();
        Object loginAdmin = session.getAttribute("loginAdmin");
        Object loginUser = session.getAttribute("loginUser");
        Object loginDoctor = session.getAttribute("loginDoctor");
        
        // 如果任一登录对象存在，则用户已登录
        if (loginAdmin == null && loginUser == null && loginDoctor == null) {
            // 未登录，根据请求路径决定重定向到哪个登录页面
            System.out.println("User not logged in, redirecting to login page");
            
            // 对于后端医生相关路径，重定向到医生登录页
            if (path.startsWith("/doctor/")) {
                httpResponse.sendRedirect(httpRequest.getContextPath() + "/toDoctorLogin");
            } 
            // 对于前端用户相关路径，重定向到前端登录页
            else if (path.startsWith("/auth/")) {
                httpResponse.sendRedirect(httpRequest.getContextPath() + "/auth/login");
            }
            // 默认重定向到管理员登录页
            else {
                httpResponse.sendRedirect(httpRequest.getContextPath() + "/toAdminLogin");
            }
        } else {
            // 已登录，继续请求
            System.out.println("User logged in, continuing request");
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        // 清理资源
    }
}